import { Form, FormField, IFormInstance } from "solid-form-context";
import { createResource, createSignal, ErrorBoundary, For } from "solid-js";
import { Table, IndexColumn, TableColumn } from "solid-table-context";
import { Dialog, useDialog } from "~/components/Dialog";
import Loading from "~/components/Loading";
import { SolidSwal2Toast } from "~/components/SolidSwal2";
import { DateTimeColumn } from "~/components/table";
import { useClientApi } from "~/services";
import {
  ClusterStateDto,
  ProxyConfigSnapshotDto,
  SnapshotDto,
} from "~/services/client";
import { handleException } from "~/services/utils";
import { is_null_or_undefined } from "~/utils/object";
import { FormJsonEdit, JsonEdit } from "./components/JsonEdit";

export default () => {
  const shell = useDialog();

  const [data, { refetch }] = createResource(() => {
    return useClientApi()
      .listSnapshots()
      .catch((err) => {
        handleException(err);
        return [] as ProxyConfigSnapshotDto[];
      });
  });

  const [loading, setLoading] = createSignal(false);
  const apply = (data: ProxyConfigSnapshotDto) => {
    setLoading(true);
    useClientApi()
      .apply(data.id)
      .then(() => {
        SolidSwal2Toast.fire({
          icon: "success",
          title: "应用成功",
        });
      })
      .catch(handleException)
      .finally(() => setLoading(false));
  };

  const [details, setDetails] = createSignal<SnapshotDto | undefined>();

  const showDetails = (data: ProxyConfigSnapshotDto): void => {
    setLoading(true);
    useClientApi()
      .getSnapshotDetails(data.id)
      .then((dto) => {
        setDetails(dto);
        shell.show();
      })
      .catch(handleException)
      .finally(() => setLoading(false));
  };

  return (
    <ErrorBoundary
      fallback={
        <button type="button" onClick={() => refetch()}>
          Try again
        </button>
      }
    >
      <Loading show={data.loading || loading()}>
        <div class="flex flex-1 px-2">
          <button
            type="button"
            class="d-btn"
            disabled={data.loading}
            onClick={() => refetch()}
          >
            刷新
          </button>
        </div>
        <Table datas={data()} class="d-table">
          <IndexColumn header="No." />
          <TableColumn name={"id"} header="Snapshot ID" />
          <DateTimeColumn name={"appliedAt"} header="Applied At" />
          <DateTimeColumn name={"removedAt"} header="Removed At" />
          <TableColumn header="Actions">
            {(data: ProxyConfigSnapshotDto) => (
              <div class="flex gap-1">
                <button
                  class="d-btn d-btn-primary d-btn-sm"
                  type="button"
                  onClick={() => apply(data)}
                >
                  应用
                </button>
                <button
                  class="d-btn d-btn-sm"
                  type="button"
                  onClick={() => showDetails(data)}
                >
                  Details
                </button>
              </div>
            )}
          </TableColumn>
        </Table>
      </Loading>
      <Dialog
        destroyOnClose
        shell={shell}
        onClose={() => setDetails(undefined)}
      >
        <fieldset class="d-fieldset mb-3">
          <legend class="d-fieldset-legend mb-1">Routes</legend>
          <JsonEdit
            readOnly
            value={JSON.stringify(details()?.routes ?? [])}
            rows={10}
            class="d-textarea w-full"
          />
        </fieldset>
        <fieldset class="d-fieldset mb-3">
          <legend class="d-fieldset-legend mb-1">Clusters</legend>
          <JsonEdit
            readOnly
            value={JSON.stringify(details()?.clusters ?? [])}
            rows={10}
            class="d-textarea w-full"
          />
        </fieldset>
      </Dialog>
    </ErrorBoundary>
  );
};
